package endpoint

import (
	"encoding/json"
	"errors"
	"net/http"

	"gitee.com/daigd/v-blog-demo-go/model"
	"gitee.com/daigd/v-blog-demo-go/service"
)

// ArticleHandle 处理文章相关请求
func ArticleHandle(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	var err error
	var articles []model.Article
	switch method {
	case "POST":
		err = handleArticlePost(w, r)
	case "GET":
		// 只实现列表查询
		articles, err = handleArticleList(w, r)
	default:
		err = errors.New("找不到对应的请求方法")
	}
	vo := model.ResultVO{Code: 200, Desc: "处理成功"}

	if err != nil {
		vo.Code = 915
		vo.Desc = err.Error()
	}
	if len(articles) > 0 {
		vo.Data = articles
	}
	bytes, _ := json.MarshalIndent(&vo, "", "\t")
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(200)
	w.Write(bytes)
}

// handlePost 处理POST请求
func handleArticlePost(w http.ResponseWriter, r *http.Request) error {
	var article model.Article
	err := json.NewDecoder(r.Body).Decode(&article)
	if err != nil {
		return err
	}
	return service.Save(&article)
}

func handleArticleList(w http.ResponseWriter, r *http.Request) (articles []model.Article, err error) {
	return service.ListArticle()
}
